'''
launcher.py
'''
# -*- coding: UTF-8 -*-
import struct,io,sys,time
from subprocess import PIPE,Popen
import threading
from iounit import IoUnit

def stremLog(stream,code='utf-8'):
	if code:
		print(str(stream,encoding=code))
	else:
		print(stream)

class lthread(threading.Thread):
	def __init__(self,obj,func):
		threading.Thread.__init__(self)
		self.call=getattr(obj,func,None)
	def run(self):
		self.call()

class launcher():
	def __init__(self,args):
		self.args=args
		self.proc=Popen(args,stdin=PIPE,stdout=PIPE,shell=True,bufsize=4096)
		self.cmds=[]
		self.io=IoUnit(self.proc)

	def _read_(self):
		return self.io.readBytes()

	def _write_(self):
		if len(self.cmds)==0:
			return
		cmd=self.cmds.pop(0)		
		self.io.sendBytes(cmd)

	def sendLine(self,line):
		self.cmds.append(bytes(line,encoding='utf-8'))

	def dealRead(self):
		print("deal read thread run up.")
		while True:
			time.sleep(0.1)
			data=self._read_()
			stremLog(data)
		print("deal read thread over.")

	def dealWrite(self):
		print("deal write thread run up.")
		while True:
			time.sleep(0.1)
			self._write_()
		print("dela write threa over.")

	def go(self):
		self.lread=lthread(self,'dealRead')
		self.lwrite=lthread(self,'dealWrite')

		self.lread.start()
		self.lwrite.start()

if __name__=="__main__":
	l=launcher("launcher.test.py")
	l.go()
	while True:
		time.sleep(0.1)
		cmd=sys.stdin.readline()		
		l.sendLine(cmd.strip())
	print("exit all process")